package com.translation.dict;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Iterator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.translation.dao.BaseDAO;
import com.translation.dao.Batch;

public class IndexImporter {

	public static void main(String[] args) throws IOException, SQLException {
		BufferedReader r = null;
		try {
			r = new BufferedReader(new FileReader(args[0]));
			final BufferedReader r1 = r;
			Iterator<String> it = new Iterator<String>() {

				Pattern p = Pattern.compile("^([^0-9\\s][^\\t]*)");

				@Override
				public void remove() {
				}

				@Override
				public String next() {
					String word = null;
					try {
						String line;
						while (word == null && (line = r1.readLine()) != null) {
							Matcher m = p.matcher(line);
							if (m.find()) {
								word = m.group(1);
							}
						}
					} catch (Exception e) {
					}
					return word;
				}

				@Override
				public boolean hasNext() {
					return true;
				}
			};

			Batch batch = getBatch(it, args[1]);
			BaseDAO dao = new BaseDAO();
			dao.namedBatch("index", batch);

		} finally {
			if (r != null) {
				r.close();
			}
		}
	}

	private static Batch getBatch(final Iterator<String> it, final String locale_id) {
		return new Batch() {

			private String word;

			@Override
			public void setParams(PreparedStatement st) throws SQLException {
				int index = 1;
				st.setString(index++, word);
				st.setString(index++, locale_id);
			}

			@Override
			public boolean result(int[] result, PreparedStatement st) throws SQLException {
				return true;
			}

			@Override
			public boolean next() throws SQLException {
				word = it.next();
				return word != null;
			}

			@Override
			public int getSize() {
				return 100;
			}
			@Override
			public void error(SQLException e) {
				if (word != null) {
					System.out.println("Near:" + word);
				}
			}
		};
	}
}
